/**
 * 该文件是一些抽出的公共的方法
 */
import Toast from '../miniprogram_npm/@vant/weapp/toast/toast';
import { getDatetime } from './util';
const $api = require('../request/api').API;
const app = getApp();

/**
 * 设置当前页面tabbar的索引
 */
export function setTabBarIndex(index) {
  const page = getCurrentPages().at(-1);
  if (typeof page.getTabBar === 'function' && page.getTabBar()) {
    if (wx.getStorageSync('access_token')) {
      $api.checkoutIsReadCount({}).then(res => {
        page.getTabBar().setData({
          msgCount: res.data.data
        });
      });
    }

    page.getTabBar().setData({
      currentindex: index
    });
  }
}
/**
 * 购物车存储
 */
export function setShopCartStorage(shopCartData) {
  wx.setStorageSync('shopCartData', JSON.stringify(shopCartData || []));
}
/**
 * 获取购物车存储
 */
export function getShopCartStorage() {
  return JSON.parse(wx.getStorageSync('shopCartData') || '[]');
}

/**
 * 清空购物车
 */
export function clearShopCartStorage() {
  wx.setStorageSync('shopCartData', JSON.stringify([]));
  wx.setStorageSync('formList', JSON.stringify([]));
}

/**
 * 事件18和19表示对接
 */
export function isDockingEvent(eventId) {
  if (eventId == 18 || eventId == 19) {
    return eventId;
  }
}
/**
 * 只能购买一件产品的时候，对不同对接事件的提示
 */
export function exceedMessageTip({ eventId, shopCartList, goods }) {
  shopCartList = shopCartList || JSON.parse(wx.getStorageSync('shopCartData') || []);
  if (!shopCartList.length) return;
  let msg = '';
  if (isDockingEvent(eventId)) {
    switch (eventId) {
      case 18:
        msg = '只能挂号一个';
        break;
      case 19:
        msg = '不能添加多个';
        break;
    }
    Toast.fail(msg);
    return true;
  } else if (goods && goods.goodsType == 4) {
    if (shopCartList.find(item => item.goodsType == 4)) Toast.fail('类产品只能添加一个');
    return true;
  }
}
/**
 * 购物车类型是否不同
 */
export function isDeferConfirmWay(businessConfirmWay, shopCartList) {
  shopCartList = shopCartList || JSON.parse(wx.getStorageSync('shopCartData') || '[]');
  if (shopCartList.length && businessConfirmWay != shopCartList[0].businessConfirmWay) {
    Toast.fail('该产品与已选产品类型不一致，不可一同购买！');
    return true;
  }
}
/**
 *判断产品是不是在活动范围内
 */
export function isActiveTime(goods) {
  if (!goods || !goods.active) return;
  const { active } = goods;
  let beginDate = getDatetime(active.beginDate).getTime();
  let endDate = getDatetime(active.endDate).getTime();
  let nowDate = new Date().getTime();
  if (nowDate > beginDate && nowDate < endDate) {
    return true;
  }
}
/**
 * 遍历产品列表如果有活动，就添加活动折扣数量修改价格
 */
export function calcuActive(goodsList) {
  let val = Array.isArray(goodsList) ? goodsList : [goodsList];
  val.forEach(item => {
    const { active, price } = item;
    if (!active || !isActiveTime(item)) {
      if (item.hasOwnProperty('activeDiscount')) delete item.activeDiscount;
      if (item.hasOwnProperty('activeNums')) delete item.activeNums;
    } else {
      item.activeDiscount = parseFloat(((active.activePrice / price) * 10).toFixed(2)) || 10;
      item.activeNums = active.maxNum;
    }
  });
  return goodsList;
}

// 遍历哪些产品是否在销售时间内
export function iterateTimeout(goodsList) {
  goodsList.forEach(item => {
    let res = null;
    if (!item.goodsHours || (item.goodsHours && !item.goodsHours.length)) {
      return;
    }
    res = item.goodsHours.some(item => {
      let time = new Date();
      let begin = new Date();
      let end = new Date();
      const arr = item.beginHours.split(':').map(item => Number(item));
      const arr2 = item.endHours.split(':').map(item => Number(item));
      begin.setHours(arr[0]);
      begin.setMinutes(arr[1]);
      end.setHours(arr2[0]);
      end.setMinutes(arr2[1]);
      return time.getTime() > begin.getTime() && time.getTime() < end.getTime();
    });
    if (!res) {
      item.nums = 0;
      item.saleState = 0;
    }
  });
  return goodsList;
}
/**
 *  判断某个产品是否超时
 * @param {number} goodsId -产品id
 * @param {array} goodsList -产品列表
 * @returns 如果有超时就修改那个产品状态并返回那个产品
 */
export function timeOut(goodsId, goodsList) {
  let goods = goodsList.find(item => item.goodsId == goodsId);
  if (!goods || !goods.goodsHours || (goods.goodsHours && !goods.goodsHours.length)) return;
  const res = goods.goodsHours.some(item => {
    let time = new Date();
    let begin = new Date();
    let end = new Date();
    const arr = item.beginHours.split(':').map(item => Number(item));
    const arr2 = item.endHours.split(':').map(item => Number(item));
    begin.setHours(arr[0]);
    begin.setMinutes(arr[1]);
    end.setHours(arr2[0]);
    end.setMinutes(arr2[1]);
    return time.getTime() > begin.getTime() && time.getTime() < end.getTime();
  });
  if (!res) {
    goods.nums = 0;
    goods.saleState = 0;
    return goods;
  } else {
    return false;
  }
}
/**
 * 给产品里面的一些数据格式化所需要的 ,例如活动、销售时间等
 */
export function formatGoodsList(goodsList) {
  calcuActive(goodsList);
  iterateTimeout(goodsList);
  return goodsList;
}

/**
 * 判断产品是否可以添加购物车
 * @param {object} goods 产品
 * @param {array} shopCartList 购物车产品数据，可不传直接从本地存储获取
 */
export function isAllowAddCart({ eventId, goods, shopCartList }) {
  const { businessConfirmWay, doctorId, active } = goods;
  shopCartList = shopCartList || JSON.parse(wx.getStorageSync('shopCartData') || '[]');
  if (isDockingEvent(eventId)) {
    if (eventId == 18) {
      // 是对接产品且是，18的时候保存doctorId
      app.globalData['dock.doctorId'] = doctorId;
    }
  }
  // 对于一些产品类型需要判断是不是只能购买一次
  if (exceedMessageTip({ eventId, shopCartList, goods })) return;

  // 判断是不是同样的购买方式
  if (isDeferConfirmWay(businessConfirmWay, shopCartList)) return;

  // 如果是活动产品且不是在活动时间内
  if (active && !isActiveTime(goods)) return;
  return true;
}

/**
 * 删除全局关于购买的数据
 */
export function deleteGLobalDataBtnList() {
  delete app.globalData['btnList.beeperId'];
  delete app.globalData['btnList.latitude'];
  delete app.globalData['btnList.longitude'];
  delete app.globalData['btnList.provinceName'];
  delete app.globalData['btnList.cityName'];
  delete app.globalData['btnList.areaName'];
  delete app.globalData['btnList.btnId'];
  delete app.globalData['btnList.btnServerClassifyIds'];
  delete app.globalData['btnList.queryType'];
  delete app.globalData['btnList.btnType'];
  delete app.globalData['btnList.addressType'];
  delete app.globalData['btnList.linkUrl'];
  delete app.globalData['btnList.eventId'];
  delete app.globalData['dock.date'];
  delete app.globalData['dock.doctorId'];
  delete app.globalData['dock.patientId'];
  delete app.globalData['dock.timerinterval'];
  delete app.globalData['btnList.variantId']; // 表单里面身份证调用接口的时候会有需要这个参数
}

/**
 * 添加表单数据进入本地存储
 */
export function addFormDataStorage(formData) {
  let formList = JSON.parse(wx.getStorageSync('formList') || '[]');
  const { name, introduce, list, id } = formData;
  formList.push({
    id,
    name,
    introduce,
    list
  });
  wx.setStorageSync('formList', JSON.stringify(formList));
}
/**
 * 获取单个产品的表单数据
 */
export async function getFormList(goods) {
  const { serverId, goodsId, thirdClassifyId, businessId } = goods;
  let res = await $api.getFormItemInfo({ serverId, goodsId, thirdClassifyId, businessId });
  res = res.data.data || [];
  return {
    id: goodsId + '-' + serverId,
    name: res[0].goodsName || res[0].serverName,
    introduce: res[0].introduce,
    list: res
  };
}
/**
 * 获取单本产品地存储的数据
 * @param {object} goods goods存在，根据goods寻找本地存储对应的表单数据，goods不存在返回本地存储所有的表单数据
 * @returns 如果goods存在就根据goods寻找本地存储对应的表单数据，找到了就返回一个带isStorage的数据，
 * 真实的表单数据，是formData属性，goods没有找到本地存储没有就调接口获取表单数据
 */
export async function getFormListStorage(goods) {
  const formList = JSON.parse(wx.getStorageSync('formList') || '[]');
  if (goods) {
    const { serverId, goodsId } = goods;
    const target = formList.find(item => item.id == goodsId + '-' + serverId);
    if (target) return { isStorage: true, ...target }; // 在本地存储找到了
    // 本地存储没有找到就通过调接口获取
    return await getFormList(goods);
  }
  return formList;
}
/**
 * 格式化表单数据
 */
export function formatFormList(formList) {
  return formList.map(item => {
    let { fieldType, value, fieldOptions } = item;
    value = value || '';
    fieldOptions = fieldOptions ? JSON.parse(item.fieldOptions) : [];
    switch (fieldType) {
      case 2:
        if (value) {
          let temp = value.split(',');
          let str = '';
          if (fieldOptions.length) {
            temp.forEach(item => {
              let name = fieldOptions.find(item2 => item2.id == item).name;
              str = str ? `${str},${name}` : name;
            });
          } else {
            str = temp;
          }
          value = str;
        }
      case 3:
        const arr = value.split(',');
        if (value && arr.length > 1) {
          value = arr[0] + ' - ' + arr[1];
        }
        break;
      case 4:
        value && (value = value.split(','));
        break;
      case 6:
        if (value && fieldOptions.length && typeof fieldOptions[0] == 'object') {
          value = fieldOptions.find(item => item.id == value).name;
        }
        break;
      case 7:
        value && (item.value = JSON.parse(value).address);
        break;
    }
    return {
      ...item,
      value
    };
  });
}
/**
 * 删除空的子节点并把每一项的id变为字符串,该函数主要是为了栋单元层组件使用，并且为了
 * 适配cascader需要填写把id变为字符串
 */
export function deEmptyChildrenCascader(arr) {
  arr.forEach(item => {
    item.id = String(item.id);
    if (!item.children) return;
    if (!item.children.length) return Reflect.deleteProperty(item, 'children');
    deEmptyChildrenCascader(item.children);
	});
	return arr;
}

/**
 * 根据树节点id查找树路径，返回一条完整的树数组
 * @param {Array} tree - 树结构数组
 * @param {string} id - 目标节点ID
 * @returns {Array} - 包含完整路径的数组
 */
export function findPathDFS(tree, id) {
  for (const node of tree) {
    if (node.id === id) {
      return node;
    }
    if (node.children) {
      const foundNode = findPathDFS(node.children, id);
      if (foundNode) {
        return foundNode;
      }
    }
  }
  return null;
}

/**
 * 根据ID去重对象数组
 * @param {Array} arr - 对象数组
 * @returns {Array} - 去重后的对象数组
 */
export function deduplicateArray(arr) {
  const seen = new Set();
  const result = [];

  for (const item of arr) {
    if (!seen.has(item.id)) {
      seen.add(item.id);
      result.push(item);
    }
  }

  return result;
}

/**
 * 使用正则表达式匹配电话号码中的数字，并将中间四位替换为 ***
 * @param phoneNumber
 * @returns phoneNumber
 */
export function maskPhoneNumber(phoneNumber) {
  return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}
/**
 * 停止录音，并且移除播放声音监听的一些函数
 */
export function clearAudioFn(innerAudioContext, options = {}) {
  const { onPlay, onPause, onStop, onEnded } = options;
  innerAudioContext.stop();
  innerAudioContext.offPlay(onPlay);
  innerAudioContext.offPause(onPause);
  innerAudioContext.offStop(onStop);
  innerAudioContext.offPlay(onEnded);
}

/**
 * 设备解除报警后的逻辑处理
 * @param id
 * @param _this
 */
export function clearAlertRefresh(id, _this) {
  const page = getCurrentPages().find(item => item.route == 'pages/equipment/index');
  const { callingList } = page.data;
  const target = callingList.find(item => item.relationId == id);
  target.errorState = 0;
  page.setData({
    callingList
  });
  _this.getData();
}
